package com.drought.rained.auth;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.drought.rained.R;
import com.drought.rained.adapter.ContactAdapterLJ;
import com.drought.rained.base.BaseTitleActivity;
import com.drought.rained.bean.AuthInfoDataLJ;
import com.drought.rained.bean.ContactItemInfoDataLJ;
import com.drought.rained.bean.DictionaryItemDataLJ;
import com.drought.rained.business.AuthRouterLJ;
import com.drought.rained.business.RouterMapLJ;
import com.drought.rained.cache.UserInfoLJ;
import com.drought.rained.common.ConstantLJ;
import com.drought.rained.mvpview.ContactMvpViewLJ;
import com.drought.rained.mvpview.DictionaryMvpViewLJ;
import com.drought.rained.permission.IPermissonLJ;
import com.drought.rained.permission.PermissionLJ;
import com.drought.rained.presenter.ContactPresenterLJ;
import com.drought.rained.presenter.DictionaryPresenterLJ;
import com.drought.rained.response.AuthInfoResponseLJ;
import com.drought.rained.response.BlankResponseLJ;
import com.drought.rained.utils.ToastUtilsLJ;
import com.drought.rained.view.MenuDialogLJ;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(name = "通讯录认证", path = RouterMapLJ.CONTACT_AUTH_PAGE)
public class ContactAuthActivityLJ extends BaseTitleActivity implements IPermissonLJ, ContactMvpViewLJ, DictionaryMvpViewLJ {
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.tv_next_step)
    TextView tvNextStep;
    @Autowired(name = ConstantLJ.IS_BACK)
    boolean is_back;

    private PermissionLJ permission;
    private ContactPresenterLJ contactPresenter;
    private ContactAdapterLJ adapter;
    private List<AuthInfoDataLJ.ContactsInfoBean.ContactsInfosBean> data = new ArrayList<>();
    private ArrayList<DictionaryItemDataLJ> dictionaryList;
    private MenuDialogLJ mMenuDialog;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }

    @Override
    protected void onUIReady() {
        ARouter.getInstance().inject(this);
        permission = new PermissionLJ(this, this);
        contactPresenter = new ContactPresenterLJ(this);
        DictionaryPresenterLJ dictionaryPresenter = new DictionaryPresenterLJ(this);
        List<String> type = new ArrayList<>();
        type.add("common_relation");
        dictionaryPresenter.getDictionaryData(type);
        LinearLayoutManager lm = new LinearLayoutManager(this);
        rv.setLayoutManager(lm);
        for (int i = 0; i < 5; i++) {
            AuthInfoDataLJ.ContactsInfoBean.ContactsInfosBean itemInfo = new AuthInfoDataLJ.ContactsInfoBean.ContactsInfosBean();

            data.add(itemInfo);
        }

        adapter = new ContactAdapterLJ(this, data);
        rv.setAdapter(adapter);
        if (UserInfoLJ.isShowUserInformation())
            contactPresenter.getContactInfo();
        if (is_back) {
            tvNextStep.setText(R.string.save_change);
        }
        adapter.setOnSelectRelationListener(new ContactAdapterLJ.OnSelectRelationListener() {
            @Override
            public void onClick(View view, int position) {
                handleDataAndShowDialog((EditText) view);
            }
        });

        adapter.setOnSelectContactListener(new ContactAdapterLJ.OnSelectContactListener() {
            @Override
            public void onClick(View view, int position) {

                permission.contactPermisson(position);
            }
        });
        rv.smoothScrollToPosition(0);

    }

    @Override
    public void onSuccess(int result) {
        selectContact(result);
    }

    public void selectContact(int request) {
        View currentFocus = (this).getCurrentFocus();
        if (currentFocus != null) {
            currentFocus.clearFocus();
        }

        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);

        startActivityForResult(intent, request);
    }

    private void handleDataAndShowDialog(EditText edit_text_relation) {
        if (dictionaryList != null && dictionaryList.size() > 0) {
            getMenuDialog().showDialog(edit_text_relation, dictionaryList);
        }
    }

    public MenuDialogLJ getMenuDialog() {
        if (mMenuDialog == null) {
            mMenuDialog = new MenuDialogLJ(this, R.style.dialog_bottom_full);
        }
        return mMenuDialog;
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_contact_auth_lj;
    }

    @Override
    public String getPageTitle() {
        return getStringResource(R.string.contact_auth_page_name);
    }


    @Override
    public void onGetDataError(Throwable throwable) {
        dismissLoadingView();
    }

    @Override
    public void onGetDataNext(BlankResponseLJ response) {
        dismissLoadingView();
        if (response.getStatus() == ConstantLJ.HTTP_OK) {
            if (!is_back) {
                AuthRouterLJ.getInstance().jumpNextPager(this, RouterMapLJ.CONTACT_AUTH_PAGE);
            } else {
                finish();
            }
        } else {
            ToastUtilsLJ.showShort(this, response.getMessage());
        }
    }

    @Override
    public void onGetDataNext(AuthInfoResponseLJ response) {
        for (int index = 0; index < response.getData().getContactsInfo().getContactsInfos().size(); index++) {
            AuthInfoDataLJ.ContactsInfoBean.ContactsInfosBean info = response.getData().getContactsInfo().getContactsInfos().get(index);

            data.set(index, info);
        }
        dismissLoadingView();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onGetDataNext(ArrayList<ArrayList<DictionaryItemDataLJ>> responseWrapper) {
        dictionaryList = responseWrapper.get(0);
    }


    @OnClick(R.id.tv_next_step)
    public void onClick() {
        List<ContactItemInfoDataLJ> data = new ArrayList<>();
        for (int i = 0; i < rv.getChildCount(); i++) {
            ContactItemInfoDataLJ info = new ContactItemInfoDataLJ();
            LinearLayout layout = (LinearLayout) rv.getChildAt(i);
            EditText et_name = layout.findViewById(R.id.et_name);
            EditText et_phone = layout.findViewById(R.id.et_phone);
            EditText et_relation = layout.findViewById(R.id.et_relation);
            String name = et_name.getText().toString().trim();
            String phone = et_phone.getText().toString().trim();
            String relation = (String) et_relation.getTag();
            if (TextUtils.isEmpty(name)) {
                ToastUtilsLJ.showShort(this, getString(R.string.contact_auth_name_toast));
                return;
            } else if (TextUtils.isEmpty(phone)) {
                ToastUtilsLJ.showShort(this, getString(R.string.contact_auth_phone_toast));
                return;
            } else if (TextUtils.isEmpty(relation)) {
                ToastUtilsLJ.showShort(this, getString(R.string.contact_auth_relation_toast));
                return;
            }
//            if (phone.length() < 11) {
//                ToastUtilsLJ.showShort(this, getString(R.string.contact_auth_contact_err));
//                return;
//            }
            if (!checkContactRepeat(phone, i)) {
                ToastUtilsLJ.showShort(this, getString(R.string.contact_auth_contact_repeat));
                return;
            }
            info.setOrderNo(i + 1 + "");
            info.setUserName(et_name.getText().toString());
            info.setMobile(et_phone.getText().toString());
            info.setRelation((String) et_relation.getTag());

            data.add(info);
        }

        Set<String> set = new HashSet<>();
        for (ContactItemInfoDataLJ itemInfo : data) {
            set.add(itemInfo.getMobile());
        }
        if (set.size() == 5) {
            contactPresenter.saveContact(data);
            showLoadingView();

        } else {
            ToastUtilsLJ.showShort(this, getString(R.string.contact_auth_contact_repeat));
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && (requestCode >= 0 && requestCode <= 4)) {
            Uri uri = data.getData();
            if (uri != null) {
                boolean isOPPO = false;
                Cursor cursor = null;
                try {
                    cursor = getContentResolver()
                            .query(uri,
                                    new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
                                    null, null, null);

                    boolean moveToNext = cursor.moveToNext();
                    if (moveToNext) {
                        String number = cursor.getString(0);
                        String name = cursor.getString(1);
                        if (checkContactRepeat(number, -1)) {
                            AuthInfoDataLJ.ContactsInfoBean.ContactsInfosBean itemInfo = getItemData(requestCode);
                            itemInfo.setMobile(number);
                            itemInfo.setUserName(name);
                            this.data.set(requestCode, itemInfo);
                            adapter.notifyItemChanged(requestCode);
                        } else {
                            ToastUtilsLJ.showShort(this, getString(R.string.contact_auth_contact_repeat));
                        }
                    } else {
                        isOPPO = true;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    isOPPO = true;
                } finally {
                    if (cursor != null && !cursor.isClosed()) {
                        cursor.close();
                    }
                }

                if (isOPPO) {
                    adapter.setModel(true);
                    ToastUtilsLJ.showShort(this, getString(R.string.contact_auth_phone_hint_enter));
                }

            }
        }
    }

    public boolean checkContactRepeat(String number, int position) {
        for (int i = 0; i < rv.getChildCount(); i++) {
            if (position == i) {
                break;
            }
            LinearLayout layout = (LinearLayout) rv.getChildAt(i);
            EditText et_phone = layout.findViewById(R.id.et_phone);
            String phone = et_phone.getText().toString().trim();
            if (number.equals(phone)) return false;
        }

        return true;
    }

    public AuthInfoDataLJ.ContactsInfoBean.ContactsInfosBean getItemData(int position) {
        AuthInfoDataLJ.ContactsInfoBean.ContactsInfosBean info = new AuthInfoDataLJ.ContactsInfoBean.ContactsInfosBean();
        if (rv.getChildCount() - 1 >= position) {
            LinearLayout layout = (LinearLayout) rv.getChildAt(position);
            EditText et_name = layout.findViewById(R.id.et_name);
            EditText et_phone = layout.findViewById(R.id.et_phone);
            EditText et_relation = layout.findViewById(R.id.et_relation);
            String name = et_name.getText().toString().trim();
            String phone = et_phone.getText().toString().trim();
            String relation = (String) et_relation.getTag();
            String relationValue = et_relation.getText().toString().trim();
            info.setMobile(phone);
            info.setUserName(name);
            info.setOrderNo(position + 1 + "");
            info.setRelation(relation);
            info.setRelationValue(relationValue);
        }

        return info;
    }
}
